package encaps.action;

import encaps.entities.Grant;
import encaps.entities.MovieLocal;
import encaps.entities.MovieLocalHome;
import encaps.entities.UserLocal;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Labels;
import encaps.utils.EntityUtil;
import encaps.utils.SystemException;
import encaps.utils.XMLHelper;
import java.util.Date;
import java.util.HashMap;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import javax.naming.NamingException;
import org.jdom.Element;

public class DeleteCommentAction extends Action {

    public static final String DELETE_COMMENT = "deleteComment";
    protected ActionContext actionContext;

    public DeleteCommentAction(ActionContext context, Grant requiredGrant) {
        this.actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            Long cid = Long.valueOf(actionContext.getTextParameter(ID));
            String username = actionContext.getUserLogin();
            UserLocal user = EntityUtil.getUserHome().findByLogin(username);
            Long uid = user.getID();
            Long movie_id = (Long) user.getUserComments().get(cid);
            if (movie_id == null) {
                return XMLHelper.createTextMessage(Labels.getLabel(Labels.MOVIE_COMMENT_PERMISSION));
            }
            MovieLocalHome movieHome = EntityUtil.getMovieHome();
            MovieLocal movie = movieHome.findByPrimaryKey(movie_id);
            movie.removeComment(cid);

            JMSUtil.sendLogMessage(Log.DELETE,
                    uid,
                    username, new Date(), "comment",
                    cid, movie_id.toString());
            return XMLHelper.toXMLElement(movie, Labels.getLabel(Labels.VIEW_MOVIE),
                    false, username, actionContext.getUserRole(), new HashMap<String, String>());
        } catch (SystemException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        } catch (FinderException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        } catch (NamingException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        } catch (RemoveException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        }

    }
}